import json
from flask import current_app
from typing import List
from flask.json import dumps as tojson

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : jinja2template.py
@DESCRIPTION   : Custom Jinja2 template functions for CDN loading
'''

def init_template_functions(app):
    """Initialize custom template functions"""
    
    @app.template_global()
    def load_cdn(reslist: List[str] = [], env: str=None) -> str:
        """Load CDN resources based on environment and resource list
        
        Args:
            env (str): Environment type ('boot', 'zstatic', or 'mc')
            reslist (List[str]): List of resource names to load
            
        Returns:
            str: HTML string containing CDN resource tags
        """
        # Get the appropriate CDN dictionary based on environment
        cdn_dict = {}
        # 在config.py中设置默认的cdn启用设置，最终实际是在static/cdn.json中配置，如果修改该CDN配置，需要重启应用
        env = env if env else current_app.config.get('ENABLECDN', 'CDNMC')
        
        if env == 'CDNBOOT':
            cdn_dict = current_app.config.get('CDNBOOT', {})
        elif env == 'CDNZS':
            cdn_dict = current_app.config.get('CDNZS', {})
        elif env == 'CDNMC':
            cdn_dict = current_app.config.get('CDNMC', {})

        # Generate HTML for each resource
        html_parts = []
        for key in reslist:
            if key in cdn_dict:
                url = cdn_dict[key]
                if 'css' in key:
                    html_parts.append(f'<link rel="stylesheet" href="{url}">')
                elif 'js' in key:
                    html_parts.append(f'<script src="{url}"></script>')
                else:
                    html_parts.append(f'<link rel="stylesheet" href="{url}">')
                    
        return '\n'.join(html_parts)

    # You can add more custom template functions here if needed

    return app